﻿using System;
using System.Reflection;
using System.Runtime.Serialization;
using Mono.Cecil;

namespace Cubicle.Core.DataContracts
{
    [DataContract]
    [Serializable]
    public class AssemblyData
    {
        [DataMember]
        public string FullName { get; set; }

        [DataMember]
        public string ProcessorArchitecture { get; set; }

        [DataMember]
        public string ImageRuntimeVersion { get; set; }

        [DataMember]
        public bool GlobalAssemblyCache { get; set; }

        [DataMember]
        public long HostContext { get; set; }

        [DataMember]
        public string Location { get; set; }

        [DataMember]
        public string Version { get; set; }

        [DataMember]
        public bool IsFullyTrusted { get; set; }

        [DataMember]
        public string DisplayName { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Path { get; set; }

        public AssemblyData(Assembly asm)
        {
            var name = asm.GetName();
            FullName = asm.FullName;
            ProcessorArchitecture = name.ProcessorArchitecture.ToString();
            ImageRuntimeVersion = asm.ImageRuntimeVersion;
            GlobalAssemblyCache = asm.GlobalAssemblyCache;
            HostContext = asm.HostContext;
            Location = asm.IsDynamic ? "Dynamic assembly" : asm.Location;
            IsFullyTrusted = asm.IsFullyTrusted;
            Name = name.Name;
            Version = name.Version.ToString();
            DisplayName = name.CultureInfo.DisplayName;
            Path = asm.IsDynamic ? "Dynamic assembly" : asm.CodeBase;
        }

        public AssemblyData(AssemblyDefinition asm, string path = null)
        {
            FullName = asm.FullName;
            ProcessorArchitecture = asm.MainModule.Architecture.ToString();
            ImageRuntimeVersion = asm.MainModule.Runtime.ToString();
            GlobalAssemblyCache = false;
            Location = "";
            Version = asm.Name.Version.ToString();
            IsFullyTrusted = true;
            DisplayName = asm.Name.Culture;
            Name = asm.Name.Name;
            Path = path;
        }


    }
}